package com.nf.health.app.zxing;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.mydoctor.activity.MyNewDoctorActivity;
import com.nf.health.app.activity.global.WebViewActivity;
import com.nf.health.app.activity.my.pay.MyScannerPayActivity;
import com.nf.health.app.activity.myscannerdcode.BuyHardwareActivity;
import com.nf.health.app.activity.myscannerdcode.MyScannerPersonalDoctorActivity;
import com.nf.health.app.core.MyGsonBuilder;
import com.nf.health.app.customview.CircleDialogFactory;
import com.nf.health.app.http.Apis;
import com.nf.health.app.models.QRCodeBean;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;
import com.nf.health.app.zxing.camera.CameraManager;
import com.nf.health.app.zxing.camera.FlashlightManager;
import com.nf.health.app.zxing.decoding.CaptureActivityHandler;
import com.nf.health.app.zxing.decoding.InactivityTimer;
import com.nf.health.app.zxing.view.ViewfinderView;

import java.io.IOException;
import java.util.Vector;

public class CaptureActivity extends BaseActivity implements Callback,
        OnClickListener {

    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private boolean hasSurface;
    private InactivityTimer inactivityTimer;
    private boolean playBeep;
    private MediaPlayer mediaPlayer;
    private boolean vibrate;
    private static final float BEEP_VOLUME = 0.10f;
    private long time[] = new long[2];
    private boolean isTurnOn = false;
    private Button tv_flash_light;
    private LinearLayout ll_prompt;
    private SurfaceView surfaceView;

    public static String IS_FROM_HAREWARE = "is_from_hareware";
    private boolean is_from_hardware;

    private static final String REQUEST_GZ_PATIENT = "request_gz_patient";//关注医生
    private static final String REQUEST_HARDWARE_DEVICE = "request_hardware_device";//硬件设备
    private CircleDialogFactory myDialog;
    SurfaceHolder surfaceHolder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isOpen = getIntent().getBooleanExtra("isOpenDocAdviceActivity", false);
        is_from_hardware = getIntent().getBooleanExtra(IS_FROM_HAREWARE,false);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_capture);
        initViews();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (ll_prompt.getVisibility() == View.VISIBLE) {
            viewfinderView.setVisibility(View.VISIBLE);
            tv_flash_light.setVisibility(View.VISIBLE);
            ll_prompt.setVisibility(View.GONE);
            surfaceView.setVisibility(View.VISIBLE);
        }
        surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    /**
     * 处理扫描结果
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        final String resultString = result.getText();

        if (!resultString.contains("nf1000.com")) {
            /*Toast.makeText(CaptureActivity.this, "请扫描正确的二维码!",
                    Toast.LENGTH_SHORT).show();
            finish();*/

                showNotHasFountDeviced("请扫描正确的二维码");
        } else {
            if (resultString.contains("stype=0")) {//预留的,以后直接加载网页使用
                String url = resultString + "&version=" + Apis.VERSION + "&access_token=" +
                        PreferenceHelper.getString(PreferenceHelper.ACCESS_TOKEN, "") + "&platform=android";
                Bundle bundle = new Bundle();
                bundle.putString(WebViewActivity.KEY_URL, url);
                ActivityUtils.showActivity(CaptureActivity.this, WebViewActivity.class, bundle);
            } else if (resultString.contains("stype=1")) {
                if (is_from_hardware){
                    //购买硬件再次扫医生码
                    String doctorid = getDoctorId(resultString);
                    Bundle bundle1 = new Bundle();
                    bundle1.putString(MyScannerPersonalDoctorActivity.DOCTOR_ID,doctorid);
                    bundle1.putInt(MyScannerPersonalDoctorActivity.IS_LOSE_EFFIUC,2);
                    bundle1.putString(MyScannerPersonalDoctorActivity.DEVICE_CODE,getIntent().getStringExtra(MyScannerPersonalDoctorActivity.DEVICE_CODE));
                    ActivityUtils.showActivity(this,MyScannerPersonalDoctorActivity.class,bundle1);
                    finish();
                }else{
                    //扫描医生
                    provider.requestQRCode(resultString, REQUEST_GZ_PATIENT);
                }

                String doctorid = getDoctorId(resultString);
            } else if (resultString.contains("stype=2")) {
                //扫描医嘱

            } else if (resultString.contains("stype=3")) {
                if (is_from_hardware){
                    showToast("请扫描医生的二维码");
                }else{
                    //扫描硬件设备
                    provider.requestQRCode(resultString, REQUEST_HARDWARE_DEVICE);
                }

            } else if (resultString.contains("stype=4")) {
                //扫描医生登陆

            } else if (resultString.contains("stype=5")) {
                Bundle bundle = new Bundle();
                bundle.putString(Constants.PAY_URL,resultString);
                ActivityUtils.showActivity(this, MyScannerPayActivity.class,bundle);
                finish();
            } else if (is_from_hardware){
                    //购买硬件再次扫医生码
                    String doctorid = getDoctorId(resultString);
                    Bundle bundle1 = new Bundle();
                    bundle1.putString(MyScannerPersonalDoctorActivity.DOCTOR_ID,doctorid);
                    bundle1.putInt(MyScannerPersonalDoctorActivity.IS_LOSE_EFFIUC,2);
                    bundle1.putString(MyScannerPersonalDoctorActivity.DEVICE_CODE,getIntent().getStringExtra(MyScannerPersonalDoctorActivity.DEVICE_CODE));
                    ActivityUtils.showActivity(this,MyScannerPersonalDoctorActivity.class,bundle1);
                    finish();
                }else{
                    //2.3以前没有stype,只有关注医生
                    provider.requestQRCode(resultString, REQUEST_GZ_PATIENT);
                }
            }

    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {

        if (REQUEST_GZ_PATIENT.equals(actionName)) {
            iv_bk.setVisibility(View.VISIBLE);
            // hideScanView();
            String result = (String) object;
            showToast(JsonUtils.getFiledData(result, "msg"));
            ActivityUtils.skipActivity(CaptureActivity.this, MyNewDoctorActivity.class);
        } else if (REQUEST_HARDWARE_DEVICE.equals(actionName)) {
//            iv_bk.setVisibility(View.VISIBLE);
//            hideScanView();
            String result = (String) object;
            Gson gson = new MyGsonBuilder().createGson();
            QRCodeBean bean = gson.fromJson(result,QRCodeBean.class);
            if ("y".equals(bean.getData().getIsvalid())){
                //二维码有效
                Bundle bundle = new Bundle();
                bundle.putString(BuyHardwareActivity.MSG_FROM_SCAN,result);
                ActivityUtils.showActivity(CaptureActivity.this,BuyHardwareActivity.class,bundle);
                finish();
            }else{
                //二维码无效
                Bundle bundle1 = new Bundle();
                bundle1.putInt(MyScannerPersonalDoctorActivity.IS_LOSE_EFFIUC,0);
                ActivityUtils.showActivity(this,MyScannerPersonalDoctorActivity.class,bundle1);
                finish();
            }

        }
    }

    /**
     * 从扫描结果获得医生id
     *
     * @param result
     */
    private String getDoctorId(String result) {
        String id = "";
        String[] params = result.substring(result.indexOf('?') + 1, result.length()).split("&");
        for (String param : params) {
            if (param.contains("doctorid")){
                id = param.substring(param.indexOf('=')+1,param.length());
            }
        }
        return id;
    }



    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        iv_bk.setVisibility(View.VISIBLE);
//        hideScanView();
//        showDialog(JsonUtils.getResponseMessage(response));
//        showToast(JsonUtils.getFiledData(response, "msg"));
        String responseTip = "请扫描正确的二维码";
        if (REQUEST_GZ_PATIENT.equals(actionName) || REQUEST_HARDWARE_DEVICE.equals(actionName)) {
            try{
                responseTip = JsonUtils.getFiledData(response, "msg");
                 /*   showToast(responseTip);*/
                showNotHasFountDeviced(responseTip);
            }catch (Exception e){
                //showToast("请扫描正确的二维码");
                showNotHasFountDeviced(responseTip);
            }
        }else{
            hideScanView();
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
            if (handler == null) {
                handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
            }
        } catch (IOException ioe) {
            ll_prompt.setVisibility(View.VISIBLE);
            hideScanView();
            return;
        } catch (RuntimeException e) {
            hideScanView();
            ll_prompt.setVisibility(View.VISIBLE);
            return;
        }
    }

    private void hideScanView() {
        viewfinderView.setVisibility(View.GONE);
        tv_flash_light.setVisibility(View.GONE);
        surfaceView.setVisibility(View.GONE);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };
    private View iv_bk;
    private boolean isOpen;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_flash_light:

                System.arraycopy(time, 1, time, 0, time.length - 1);
                time[time.length - 1] = System.currentTimeMillis();
                if (time[time.length - 1] - time[0] > 500) {
                    Camera camera = CameraManager.get().getCamera();
                    if (null != camera) {
                        if (!isTurnOn) {
                            FlashlightManager.turnLightOn(camera);
                            tv_flash_light.setText("关闭闪光灯");
                            isTurnOn = true;
                        } else {
                            FlashlightManager.turnLightOff(camera);
                            tv_flash_light.setText("开启闪光灯");
                            isTurnOn = false;
                        }
                    } else {
                        showToast("开启闪光灯失败");
                    }
                }

                break;
            default:
                break;
        }
        super.onClick(v);
    }

    private void initData() {
        CameraManager.init(getApplication());
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
    }

    private void initViews() {
        ViewUtil.setText(this, R.id.titlebar_title_tv, "扫一扫");
        // TextView下面的父布局，点击范围更广
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        tv_flash_light = (Button) findViewById(R.id.tv_flash_light);
        iv_bk = findViewById(R.id.iv_bk);

        // v_loading = findViewById(R.id.v_loading);

        ll_prompt = (LinearLayout) findViewById(R.id.ll_prompt);

        tv_flash_light.setOnClickListener(this);
    }
    public void showNotHasFountDeviced(String msg) {
        hasSurface = false;
        surfaceHolder.removeCallback(this);
        if(myDialog == null){

            myDialog = new CircleDialogFactory(CaptureActivity.this);
            myDialog.setCircleDialogFactoryMsg(msg);
            myDialog.setCirclrDialogButtonText("确定");
            myDialog.setCircleDialogFactoryOnClicklistener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (myDialog.isShowing()) {
                        myDialog.dismiss();
                    }
                    Intent intent = new Intent(CaptureActivity.this,CaptureActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                    hasSurface = true;
                    surfaceHolder.addCallback(CaptureActivity.this);
                }
            });
            myDialog.getContentMsgCenter();
            myDialog.setCancelable(false);
            myDialog.setCircleDialogAtter(0.75, 0.35);
            myDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (myDialog != null) {
                        if (myDialog.isShowing()) {
                            myDialog.cancel();
                        }
                    }
                    finish();
                    return false;
                }
            });
        }
        if(!myDialog.isShowing()){
            myDialog.show();
        }
    }
}
